package service
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import model.ReaderModel;

	public class ReaderService
	{
		private static var instance:ReaderService;
		
		private static var allowInstance:Boolean;
		
		private static var _API_BASE:String = "http://www.tongbupan.com";
		
		/**
		 * 由外部传入的js接口函数 
		 */		
		public static var JS_API:String = "";
		
		public static var PREVIEW_CONVERT:String = API_BASE + "/link/preview/convert/";
		
		//站外
		public var linkid:String = "Dg65HoIWnzNSoWH";
		public var version:String = "";
		public var path:String = "";
		public var split:String = "yes";
		public var previewLink:String = "";		
		public var previewconvert:String = "http://www.tongbupan.com/fs/public/link/previewconvert/?linkid=2Rt0OP47yzi6qdn&path=/test.txt/&version=&split=yes&token=6KJ6lAC21nZ6BUgF511wRoX34y0&expire=1357558585";
		
		public function ReaderService()
		{
			if(!allowInstance)
			{
				throw(new Error("use ReaderService.getInstance()"));
			}
		}
		
		public static function getInstance():ReaderService
		{
			if(instance == null)
			{
				allowInstance = true;
				instance = new ReaderService();
				allowInstance = false;
			}
			return instance;
		}
		
		public function getToken():void
		{
			var ld:URLLoader = new URLLoader();		
			var val:URLVariables = new URLVariables();
			val.linkid = linkid;
			val.version = version;
			val.path = path;
			val.split = split;
			var req:URLRequest = new URLRequest(PREVIEW_CONVERT);
			req.data = val;
			req.method = URLRequestMethod.GET;
			var rh:URLRequestHeader = new URLRequestHeader("Content-Type", "charset=UTF-8");
			req.requestHeaders.push(rh);
			ld.addEventListener(Event.COMPLETE, onPreviewConvertResult);
			ld.addEventListener(IOErrorEvent.IO_ERROR, onPreviewConvertIOError);
			ld.load(req);
		}
		
		protected function onPreviewConvertResult(e:Event):void
		{
			var ld:URLLoader = e.target as URLLoader;
			var result:Object = JSON.decode(ld.data);
			previewLink =  result.data.previewlink;
			changeToken();
		}
		
		protected function onPreviewConvertIOError(event:IOErrorEvent):void
		{
			if(ReaderService.JS_API == ""){
				if(ExternalInterface.available) ExternalInterface.call("alert", "IOError: 调用preview/convert接口失败");
			}else{
				var obj:Object = {};
				obj.code = 1;
				obj.message = "IOError: 调用preview/convert接口失败";
				if(ExternalInterface.available) ExternalInterface.call(ReaderService.JS_API, JSON.encode(obj));
			}
		}
		
		private function changeToken():void
		{
			var ld:URLLoader = new URLLoader();
			ld.addEventListener(Event.COMPLETE, onChangeTokenResult);
			ld.addEventListener(IOErrorEvent.IO_ERROR, onChangeTokenIOError);
			var req:URLRequest = new URLRequest(API_BASE + previewLink);
			var rh:URLRequestHeader = new URLRequestHeader("Content-Type", "charset=UTF-8");
			req.requestHeaders.push(rh);
			ld.load(req);		
		}
		
		protected function onChangeTokenIOError(e:IOErrorEvent):void
		{
			if(ReaderService.JS_API == ""){
				if(ExternalInterface.available) ExternalInterface.call("alert", "IOError: 调用换取token 接口失败，接口地址：" + previewLink);
			}else{
				var obj:Object = {};
				obj.code = 1;
				obj.message = "IOError: 调用换取token 接口失败，接口地址：" + previewLink;
				if(ExternalInterface.available) ExternalInterface.call(ReaderService.JS_API, JSON.encode(obj));
			}
		}
		
		protected function onChangeTokenResult(e:Event):void
		{
			var ld:URLLoader = e.target as URLLoader;
			var result:Object = JSON.decode(ld.data);
			var m:ReaderModel = ReaderModel.getInstance();
			m.file_url = API_BASE + result.data.url;
			m.total_page_num = result.data.pageNum; //这两个顺序不能颠倒，由于控制了加载是否启动
		}

		public static function get API_BASE():String
		{
			return _API_BASE;
		}

		public static function set API_BASE(value:String):void
		{
			_API_BASE = value;
			PREVIEW_CONVERT = _API_BASE + "/link/preview/convert/"
		}
		
	}
	
}